package com.xauto.pioneer.appuser.activity;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.common.WebViewActivity;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.interfaces.CommonCallBack;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.util.DataLoadUtil;
import com.xauto.pioneer.appuser.util.MatcherUtil;
import com.xauto.pioneer.appuser.util.PreferencesUtils;
import com.xauto.pioneer.appuser.util.StringUtils;
import com.xauto.pioneer.appuser.util.ToastUtil;
import com.xauto.pioneer.appuser.view.PromptDialog;

import java.util.Set;

import butterknife.Bind;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.baidu.mapapi.BMapManager.getContext;

/***
 * 登录页面
 * @author Lemon Sun 12 Feb 15:49
 */
public class LoginActivity extends BaseActivity {

    /** 输入-手机号*/
    @Bind(R.id.etLoginMobile) EditText etLoginMobile;
    /** 输入-手机验证码*/
    @Bind(R.id.etLoginVerCode) EditText etLoginVerCode;
    /** 发送验证码*/
    @Bind(R.id.tvLoginSendCode) TextView tvLoginSendCode;
    private PromptDialog promptDialog;

    /** 验证码，用于验证客户是否输入正确*/
    private String verify_code;
    /** 生成的CODE,用于在提交回传服务器验证码*/
    private String code;

    @Override
    protected int getContentView() {
        return R.layout.ac_login;
    }

    @Override
    protected void initView() {
        promptDialog = new PromptDialog(mContext, getString(R.string.notice), getString(R.string.text_not_network),
                getString(R.string.to_setting), getString(R.string.logout),getString(R.string.dialogpic_notice),new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //去设置
                promptDialog.dismiss();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出
                promptDialog.dismiss();
            }
        });
    }

    @Override
    protected void initData() {
        lHandler = new BaseLHttpHandler(mContext, true, true) {

            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                String member_id = jsonStatus.data.optString("member_id");
                String token = jsonStatus.data.optString("token");
                PreferencesUtils.putString(mContext, Constants.KEY_MEMBER_ID, member_id);
                PreferencesUtils.putString(mContext, Constants.KEY_TOKEN, token);
                PreferencesUtils.putString(mContext, Constants.KEY_MEMBER_ADD, "");
                setJPushAlias(mContext,member_id);

            }
        };
    }

    @OnClick({R.id.tvLoginSendCode, R.id.llLoginAgreement, R.id.ivLoginSubmit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvLoginSendCode:
                //发送验证码
                if(StringUtils.isBlank(etLoginMobile.getText().toString())) {
                    ToastUtil.showShort(mContext, getString(R.string.mobile_is_not_empty));
                    return;
                }
                if(!MatcherUtil.Matcher(Constants.MATCHER_MOBILE, etLoginMobile.getText().toString())) {
                    ToastUtil.showShort(mContext, getString(R.string.mobile_is_error));
                    return;
                }
                loadGetVerifyCode();
                break;
            case R.id.llLoginAgreement:
                //跳转租赁协议
                WebViewActivity.startAction(mContext,3);
                break;
            case R.id.ivLoginSubmit:
                //登录
                if(verifyInput()) {
                    load();
                }
                break;
        }
    }

    void load() {
        new LHttpLib().quickLogin(mContext, etLoginMobile.getText().toString(), code, lHandler);
    }

    void loadValidMobile() {
        new LHttpLib().validateMemberInfo(mContext, Constants.TYPE_REG_LOGIN_MOBILE,
                etLoginMobile.getText().toString(), new BaseLHttpHandler(mContext, true, false) {

                    @Override
                    public void onSuccess(JSONStatus jsonStatus) {
                        super.onSuccess(jsonStatus);
                        min = 60;
                        timeRunnable.run();
                        loadGetVerifyCode();
                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        ToastUtil.showShort(getContext(), strMsg);
                        min = 0;
                    }
                });
    }

    void loadGetVerifyCode() {
        new LHttpLib().getVerifyCode(mContext, etLoginMobile.getText().toString(), new BaseLHttpHandler(mContext, true, false) {

            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                verify_code = jsonStatus.data.optString("verify_code");
                code = jsonStatus.data.optString("code");
                ToastUtil.showShort(mContext, getString(R.string.send_code_success));
                min = 60;
                timeRunnable.run();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                prompt(strMsg);
                min = 0;
            }
        });
    }


    Handler handler = new Handler(){};
    int min = 60;
    /** 倒计时*/
    Runnable timeRunnable = new Runnable() {
        @Override
        public void run() {
            if(min > 0){
                min--;
                tvLoginSendCode.setEnabled(false);
                tvLoginSendCode.setText(min + "s");
                handler.postDelayed(timeRunnable, 1000);
            }else{
                tvLoginSendCode.setText("发送验证码");
                tvLoginSendCode.setEnabled(true);
            }
        }
    };

    /** 登录验证*/
    private boolean verifyInput() {
        if(StringUtils.isBlank(etLoginMobile.getText().toString())) {
            ToastUtil.showShort(mContext, getString(R.string.mobile_is_not_empty));
            return false;
        }
        if(!MatcherUtil.Matcher(Constants.MATCHER_MOBILE, etLoginMobile.getText().toString())) {
            ToastUtil.showShort(mContext, getString(R.string.mobile_is_error));
            return false;
        }
        if(StringUtils.isBlank(etLoginVerCode.getText().toString())) {
            ToastUtil.showShort(mContext, getString(R.string.code_is_not_empty));
            return false;
        }
        if(!etLoginVerCode.getText().toString().equals(verify_code)) {
            ToastUtil.showShort(mContext, getString(R.string.code_is_error));
            return false;
        }
        return true;
    }

    /**
     * 设置别名
     * @param context
     * @param alias
     */
    private void setJPushAlias(Context context, String alias){
        // 调用 JPush 接口来设置别名。
        JPushInterface.setAliasAndTags(context, alias, null, new TagAliasCallback() {
            @Override
            public void gotResult(int code, String s, Set<String> set) {
                String logs ;
                switch (code) {
                    case 0:
                        logs = "Set tag and alias success";
                        Log.e("JPUSH", logs);
                        // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                        //设置推送信息
                        DataLoadUtil.editPushDevice(mContext, JPushInterface.getRegistrationID(mContext), new CommonCallBack() {
                            @Override
                            public void getCallBack() {
                                onBackPressed();
                            }
                        });
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                onBackPressed();
//                            }
//                        });
                        break;
                    case 6001:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "1");
                        break;
                    case 6002:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "2");
                        break;
                    case 6003:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "3");
                        break;
                    case 6004:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "4");
                        break;
                    case 6005:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "5");
                        break;
                    case 6006:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "6");
                        break;
                    case 6007:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "7");
                        break;
                    case 6008:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "8");
                        break;
                    case 6009:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "9");
                        break;
                    case 6010:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "10");
                        break;
                    case 6011:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.e("JPUSH", "11");
                        break;
                    default:
                        logs = "Failed with errorCode = " + code;
                        Log.e("JPUSH", logs);
                }
            }
        });
    }
}
